package com.walkline.screen;

import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.walkline.app.DianpingAppConfig;
import com.walkline.dianping.DianpingException;
import com.walkline.dianping.DianpingSDK;
import com.walkline.dianping.inf.Categories;
import com.walkline.dianping.inf.Cities;
import com.walkline.dianping.inf.DealIdList;
import com.walkline.dianping.inf.DealResult;
import com.walkline.dianping.inf.Regions;
import com.walkline.dianping.inf.SingleDeal;
import com.walkline.util.Function;
import com.walkline.util.ui.DealListStyleButtonField;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonSet;

public final class DianpingScreen extends MainScreen implements FieldChangeListener
{
	DianpingSDK _dianping = DianpingSDK.getInstance();
	ObjectChoiceField _choiceCities;
	ObjectChoiceField _choiceDistricts;
	ObjectChoiceField _choiceNeighborhoods;
	ObjectChoiceField _choiceCategories;
	ObjectChoiceField _choiceSubCategories;

	ObjectChoiceField _choiceCitiesWithDeals;
	ObjectChoiceField _choiceDailyNewIdList;

	Regions _regions;
	Categories _categories;

	VerticalFieldManager _dealFieldManager = new VerticalFieldManager();
	ButtonField cmdGetDailyNewIdList;
	ButtonField cmdGetDealDetails;
	ButtonField cmdTestDoubleFormat;

	ForegroundManager _foreground = new ForegroundManager(0);
	ListStyleButtonSet _dealItemSet = new ListStyleButtonSet();

    public DianpingScreen()
    {
    	super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

		String titleIconName = Display.getWidth() < 640 ? "titleIcon_small.png" : "titleIcon_large.png";
		BitmapField bmpTitleField = new BitmapField(Bitmap.getBitmapResource(titleIconName));
		bmpTitleField.setSpace(5, 5);
		LabelField labelTitleField = new LabelField(DianpingAppConfig.APP_TITLE, LabelField.ELLIPSIS);
		labelTitleField.setFont(DianpingAppConfig.FONT_MAIN_TITLE);

		HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_WIDTH);
		VerticalFieldManager vfm = new VerticalFieldManager(FIELD_VCENTER);
		vfm.add(labelTitleField);
		hfm.add(bmpTitleField);
		hfm.add(vfm);
		hfm.setBackground(DianpingAppConfig.bgColor_Gradient);
		setTitle(hfm);

		cmdGetDailyNewIdList = new ButtonField("获取每日新增团购ID列表", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		cmdGetDailyNewIdList.setChangeListener(this);

		cmdGetDealDetails = new ButtonField("获取指定团购信息", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		cmdGetDealDetails.setChangeListener(this);

		cmdTestDoubleFormat = new ButtonField("测试格式化数字", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		cmdTestDoubleFormat.setChangeListener(this);

		_choiceCities = new ObjectChoiceField("商户城市：", null, 0);
		_choiceDistricts = new ObjectChoiceField("城市区域：", null, 0);
		_choiceNeighborhoods = new ObjectChoiceField("区域周边：", null, 0);
		_choiceCategories = new ObjectChoiceField("分类：", null, 0);
		_choiceSubCategories = new ObjectChoiceField("子分类：", null, 0);

		_choiceCitiesWithDeals = new ObjectChoiceField("支持团购的城市：", null, 0);
		_choiceDailyNewIdList = new ObjectChoiceField("团购ID列表", null, 0);

		//add(_choiceCities);
		//add(_choiceDistricts);
		//add(_choiceNeighborhoods);
		//add(_choiceCategories);
		//add(_choiceSubCategories);
		//add(new SeparatorField());
		//add(cmdGetDailyNewIdList);
		//add(cmdGetDealDetails);
		//add(_choiceCitiesWithDeals);
		//add(_choiceDailyNewIdList);
		//add(_dealFieldManager);
		//add(cmdTestDoubleFormat);
		HorizontalFieldManager hfmSearch = new HorizontalFieldManager(USE_ALL_WIDTH)
		{
			protected void paintBackground(Graphics g)
			{
				super.paintBackground(g);

				g.setColor(Color.GRAY);
				g.drawRect(-1, -1, getWidth() + 2, getHeight());
			}
		};
		hfmSearch.add(new ButtonField("分类"));
		hfmSearch.add(new ButtonField("区域"));
		hfmSearch.add(new ButtonField("其它"));
		add(hfmSearch);
		_foreground.add(_dealItemSet);
		add(_foreground);
		/*
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				try {
					Cities cities = _dianping.getCitiesWithBusinesses();

					if (cities != null)
					{
						_choiceCities.setChoices(cities.getCities());
						_choiceCities.setChangeListener(new FieldChangeListener()
						{
							public void fieldChanged(Field field, int context)
							{
								try {
									_regions = _dianping.getRegionsWithBusinesses((String) _choiceCities.getChoice(_choiceCities.getSelectedIndex()));
								} catch (DianpingException e) {}

								if (_regions != null)
								{
									_choiceDistricts.setChoices(_regions.getDistricts());
									_choiceDistricts.setSelectedIndex(0);

									if (_choiceDistricts.getChangeListener() == null)
									{
										_choiceDistricts.setChangeListener(new FieldChangeListener()
										{
											public void fieldChanged(Field field, int context)
											{
												if (context != FieldChangeListener.PROGRAMMATIC)
												{
													_choiceNeighborhoods.setChoices(_regions.getNeighborhoods((String) _choiceDistricts.getChoice(_choiceDistricts.getSelectedIndex())));
												}
											}
										});
									}

									_choiceNeighborhoods.setChoices(_regions.getNeighborhoods((String) _choiceDistricts.getChoice(_choiceDistricts.getSelectedIndex())));
								}
							}
						});
						_choiceCities.setSelectedIndex(_dianping.getPhoneNumberProvince());
					}
				} catch (DianpingException e) {Function.errorDialog(e.toString());}	
			}
		});
		*/

		/*
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				try {
					_categories = _dianping.getCategoriesWithBusinesses();

					_choiceCategories.setChoices(_categories.getCategoriesName());

					if (_choiceCategories.getChangeListener() == null)
					{
						_choiceCategories.setChangeListener(new FieldChangeListener()
						{
							public void fieldChanged(Field field, int context)
							{
								_choiceSubCategories.setChoices(_categories.getSubCategoriesName(_choiceCategories.getChoice(_choiceCategories.getSelectedIndex())));
							}
						});
					}

					_choiceSubCategories.setChoices(_categories.getSubCategoriesName(_choiceCategories.getChoice(_choiceCategories.getSelectedIndex())));
				} catch (DianpingException e) {Function.errorDialog(e.toString());}	
			}
		});
		*/

		/*
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run() 
			{
				try {
					Cities cities = _dianping.getCitiesWithDeals();

					if (cities != null)
					{
						_choiceCitiesWithDeals.setChoices(cities.getCities());
					}
				} catch (DianpingException e) {Function.errorDialog(e.toString());}
			}
		});
		*/

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String today = sdf.formatLocal(System.currentTimeMillis());
				String city = _dianping.getPhoneNumberProvince();

				//try {
					//Cities cities = _dianping.getCitiesWithDeals();

					//if (cities != null)
					//{
					//	_choiceCitiesWithDeals.setChoices(cities.getCities());
					//}
				//} catch (DianpingException e) {Function.errorDialog(e.toString());}

				try {
					//DealIdList idList = _dianping.getDailyNewIdList((String) _choiceCitiesWithDeals.getChoice(_choiceCitiesWithDeals.getSelectedIndex()), today);
					DealIdList idList = _dianping.getDailyNewIdList(city, today);
					DealResult dealResult = _dianping.getDealsDetail(idList.getIDList(8));

					for (int i=0; i<dealResult.getCounts(); i++)
					{
						DealListStyleButtonField item = new DealListStyleButtonField(dealResult.getDeals()[i]);
						_dealItemSet.add(item);
					}
				} catch (DianpingException e) {Function.errorDialog(e.toString());}
			}
		});
	}

    protected boolean onSavePrompt() {return true;}

	public void fieldChanged(Field field, int context)
	{
		if (field.equals(cmdGetDailyNewIdList))
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String today = sdf.formatLocal(System.currentTimeMillis());

			try {
				DealIdList idList = _dianping.getDailyNewIdList((String) _choiceCitiesWithDeals.getChoice(_choiceCitiesWithDeals.getSelectedIndex()), today);

				_choiceDailyNewIdList.setChoices(idList.getIDList());

				DealResult dealResult = _dianping.getDealsDetail(idList.getIDList(3));

				for (int i=0; i<dealResult.getCounts(); i++)
				{
					DealListStyleButtonField item = new DealListStyleButtonField(dealResult.getDeals()[i]);
					_dealItemSet.add(item);
				}
			} catch (DianpingException e) {Function.errorDialog(e.toString());}
		} else if (field.equals(cmdGetDealDetails)) {
			try {
				String[] a = {(String) _choiceDailyNewIdList.getChoice(_choiceDailyNewIdList.getSelectedIndex())};
				String[] b = new String[3];
				for (int i=0; i<3; i++)
				{
					b[i] = (String) _choiceDailyNewIdList.getChoice(i);	
				}

				DealResult dealResult = _dianping.getDealsDetail(b);
				SingleDeal deal = dealResult.getDeals()[0];

				if (_dealFieldManager.getFieldCount() != 0) {_dealFieldManager.deleteAll();}

				_dealFieldManager.add(new LabelField("团购单ID: " + deal.getDealID(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购标题: " + deal.getTitle(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购描述: " + deal.getDescription(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购城市: " + deal.getCity(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("商品原价: " + String.valueOf(deal.getListPrice()), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("商品现价: " + String.valueOf(deal.getCurrentPrice()), LabelField.FOCUSABLE));
				_dealFieldManager.add(new ObjectChoiceField("区域：", deal.getRegions()));
				_dealFieldManager.add(new ObjectChoiceField("分类：", deal.getCategories()));
				_dealFieldManager.add(new LabelField("已购买数量: " + String.valueOf(deal.getPurchaseCount()), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("截止日期: " + deal.getPurchaseDeadline(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("发布日期: " + deal.getPublishDate(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购详情: " + deal.getDetails(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购大图链接: " + deal.getImageURL(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购小图链接: " + deal.getSmallImageURL(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new ObjectChoiceField("更多大图：", deal.getMoreImageURLs()));
				_dealFieldManager.add(new ObjectChoiceField("更多小图：", deal.getMoreSmallImageURLs()));
				_dealFieldManager.add(new LabelField("是否热门: " + String.valueOf(deal.getIsPopular()), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("是否需要预约: " + String.valueOf(deal.getIsReservationRequired()), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("是否随时退款: " + String.valueOf(deal.getIsRefundable()), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("特别提示: " + deal.getSpecialTips(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("重要通知: " + deal.getNotice(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购Web页面: " + deal.getDealURL(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("团购HTML5页面: " + deal.getDealHTML5URL(), LabelField.FOCUSABLE));
				_dealFieldManager.add(new LabelField("佣金比例: " + String.valueOf(deal.getCommissionRatio()), LabelField.FOCUSABLE));
			} catch (DianpingException e) {Function.errorDialog(e.toString());}
		} else if (field.equals(cmdTestDoubleFormat)) {
			Function.errorDialog("" + (long) 100.04D);
		}
	}
}